<script setup>
import { Plus, Refresh, Delete, Upload, Download } from '@element-plus/icons-vue'
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  addDormRoom, updateDormRoom, deleteDormRoom, batchDeleteDormRoom,
  getDormRoomPage, getDormRoomByBuilding
} from '@/api/dormRoom'
import { getDormBuildingPage } from '@/api/dormBuilding'

onMounted(() => {
  loadBuildings()
  getData()
})

const loading = ref(false)
const tableData = ref([])
const pagination = ref({ currentPage: 1, pageSize: 10, total: 0 })
const selectedRows = ref([])
const multipleTableRef = ref()

const buildings = ref([])
const buildingOptions = ref([])
const buildingLabelMap = ref({})

const queryForm = ref({ buildingId: null, roomNo: '', roomStatus: '' })

const dialogFormVisible = ref(false)
const title = ref('')
const formRef = ref(null)
const formData = ref({
  id: '',
  buildingId: null,
  roomNo: '',
  bedCount: null,
  occupiedCount: 0,
  roomType: '',
  roomStatus: '',
  description: ''
})

const rules = {
  buildingId: [{ required: true, message: '请选择楼宇', trigger: 'change' }],
  roomNo: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  bedCount: [{ required: true, message: '请输入床位总数', trigger: 'blur' }]
}

const loadBuildings = () => {
  getDormBuildingPage({ currentPage: 1, pageSize: 1000 }).then(res => {
    const page = res.data || {}
    buildings.value = page.list || []
    
    buildingOptions.value = buildings.value.map(b => ({ label: `${b.buildingNo}-${b.buildingName}`, value: b.id }))
    buildingLabelMap.value = Object.fromEntries(buildingOptions.value.map(o => [o.value, o.label]))
    console.log(buildingOptions.value)
  })
}

const getData = () => {
  loading.value = true
  getDormRoomPage({ currentPage: pagination.value.currentPage, pageSize: pagination.value.pageSize })
    .then(res => {
      console.log(res)
      const page = res.data || {}
      tableData.value = page.list || []
      pagination.value.total = page.total || 0
      const { buildingId, roomNo, roomStatus } = queryForm.value
      if (buildingId) tableData.value = tableData.value.filter(it => it.buildingId === buildingId)
      if (roomNo) tableData.value = tableData.value.filter(it => it.roomNo && it.roomNo.includes(roomNo))
      if (roomStatus) tableData.value = tableData.value.filter(it => it.roomStatus === roomStatus)
    })
    .catch(err => ElMessage.error(err.message || '获取数据失败'))
    .finally(() => loading.value = false)
}

const handleSizeChange = (val) => { pagination.value.pageSize = val; pagination.value.currentPage = 1; getData() }
const handleCurrentChange = (val) => { pagination.value.currentPage = val; getData() }
const handleSelectionChange = (rows) => { selectedRows.value = rows }

const reset = () => {
  formData.value = { id: '', buildingId: null, roomNo: '', bedCount: null, occupiedCount: 0, roomType: '', roomStatus: '', description: '' }
}
const cancel = () => { dialogFormVisible.value = false; reset() }

const handleAddModel = () => { dialogFormVisible.value = true; title.value = '新增房间'; reset() }
const handleEdit = (row) => { dialogFormVisible.value = true; title.value = '编辑房间'; formData.value = { ...row } }

const submitForm = () => {
  formRef.value.validate(valid => {
    if (!valid) return
    const api = formData.value.id ? updateDormRoom : addDormRoom
    api(formData.value).then(res => {
      if (res.code === 200) {
        ElMessage.success(res.message)
        console.log(res)
        cancel(); getData()
      } else {
        ElMessage.error(res.message)
      }
    }).catch(err => ElMessage.error(err.message))
  })
}

const handleDelete = (id) => {
  ElMessageBox.confirm('此操作将删除该房间, 是否继续?', '提示', { type: 'warning' })
    .then(() => deleteDormRoom(id))
    .then(res => { if (res.code === 200) { ElMessage.success(res.message); getData() } else { ElMessage.error(res.message) } })
    .catch(() => {})
}

const handleBatchDelete = () => {
  if (!selectedRows.value.length) return ElMessage.warning('请至少选择一条数据')
  const ids = selectedRows.value.map(r => r.id)
  ElMessageBox.confirm(`此操作将永久删除选中的 ${ids.length} 条数据, 是否继续?`, '提示', { type: 'warning' })
    .then(() => batchDeleteDormRoom(ids))
    .then(res => {
      if (res.code === 200) { ElMessage.success(res.message); getData(); multipleTableRef.value?.clearSelection() } else { ElMessage.error(res.message) }
    })
    .catch(() => {})
}

const handleSearch = () => { pagination.value.currentPage = 1; getData() }
const handleResetQuery = () => { queryForm.value = { buildingId: null, roomNo: '', roomStatus: '' }; getData() }

// 导入成功回调
const importExcelSuccess = (res) => {
  if (res && res.code === 200) {
    ElMessage.success(res.message || '导入成功')
    getData()
  } else {
    ElMessage.error((res && res.message) || '导入失败')
  }
}

// 导出
const handleExportExcel = () => {
  window.open('http://localhost:8080/api/dormRoom/export')
}

const getRoomStatusType = (s) => {
  switch (s) {
    case '空闲': return 'success'
    case '部分空闲': return 'warning'
    case '已满': return 'danger'
    case '维修中': return 'info'
    default: return ''
  }
}
</script>

<template>
  <div class="card">
    <div class="toolbar">
      <el-select v-model="queryForm.buildingId" placeholder="选择楼宇" style="width: 220px" filterable clearable>
        <el-option v-for="b in buildingOptions" :key="b.value" :label="b.label" :value="b.value"/>
      </el-select>
      <el-input v-model="queryForm.roomNo" placeholder="房间号" style="width: 180px" clearable/>
      <el-select v-model="queryForm.roomStatus" placeholder="房间状态" style="width: 160px" clearable>
        <el-option label="空闲" value="空闲"/>
        <el-option label="部分空闲" value="部分空闲"/>
        <el-option label="已满" value="已满"/>
        <el-option label="维修中" value="维修中"/>
      </el-select>
      <el-button type="primary" :icon="Refresh" @click="handleSearch">查询</el-button>
      <el-button @click="handleResetQuery">重置</el-button>
    </div>
    <div class="actions">
      <el-button type="primary" :icon="Plus" @click="handleAddModel">新增</el-button>
      <el-upload :action="'http://localhost:8080/api/dormRoom/import'" :on-success="importExcelSuccess" :show-file-list="false" class="upload-excel">
        <el-button type="success" :icon="Download">导入</el-button>
      </el-upload>
      <el-button type="info" :icon="Upload" @click="handleExportExcel">导出</el-button>
      <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <el-table :data="tableData" border stripe size="small" fit highlight-current-row v-loading="loading" @selection-change="handleSelectionChange" ref="multipleTableRef">
      <el-table-column type="selection" width="50"/>
      <el-table-column label="所属楼宇" width="200">
        <template #default="scope">
          {{ buildingLabelMap[scope.row.buildingId] || scope.row.buildingId }}
        </template>
      </el-table-column>
      <el-table-column prop="roomNo" label="房间号" width="120" show-overflow-tooltip/>
      <el-table-column prop="bedCount" label="床位数" width="100"/>
      <el-table-column prop="occupiedCount" label="已入住" width="100"/>
      <el-table-column prop="roomType" label="类型" width="120"/>
      <el-table-column label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getRoomStatusType(scope.row.roomStatus)">{{ scope.row.roomStatus || '—' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="备注" show-overflow-tooltip/>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5,10,20,50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog v-model="dialogFormVisible" :title="title" width="600px" @close="reset">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" size="small">
        <el-form-item label="所属楼宇" prop="buildingId">
          <el-select v-model="formData.buildingId" placeholder="请选择" style="width: 100%" filterable clearable>
            <el-option v-for="b in buildingOptions" :key="b.value" :label="b.label" :value="b.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="房间号" prop="roomNo">
          <el-input v-model="formData.roomNo"/>
        </el-form-item>
        <el-form-item label="床位总数" prop="bedCount">
          <el-input-number v-model="formData.bedCount" :min="0" :max="1000"/>
        </el-form-item>
        <el-form-item label="已入住人数">
          <el-input-number v-model="formData.occupiedCount" :min="0" :max="1000"/>
        </el-form-item>
        <el-form-item label="房间类型">
          <el-select v-model="formData.roomType" placeholder="请选择">
            <el-option label="标准间" value="标准间"/>
            <el-option label="四人间" value="四人间"/>
            <el-option label="六人间" value="六人间"/>
            <el-option label="八人间" value="八人间"/>
          </el-select>
        </el-form-item>
        <el-form-item label="房间状态">
          <el-select v-model="formData.roomStatus" placeholder="请选择" clearable>
            <el-option label="空闲" value="空闲"/>
            <el-option label="部分空闲" value="部分空闲"/>
            <el-option label="已满" value="已满"/>
            <el-option label="维修中" value="维修中"/>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="formData.description" rows="3"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.card { background: #fff; padding: 16px; border-radius: 8px; }
.toolbar { margin-bottom: 8px; display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
.actions { margin-bottom: 12px; display: flex; align-items: center; gap: 10px; }
.pager { margin-top: 12px; display: flex; justify-content: flex-end; }
.upload-excel{ display: inline-block; }
</style>

const getRoomStatusType = (s) => {
  switch (s) {
    case '空闲': return 'success'
    case '部分空闲': return 'warning'
    case '已满': return 'danger'
    case '维修中': return 'info'
    default: return ''
  }
}